package term

import (
	"context"
	"fmt"
	"strings"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateTermLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateTermLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateTermLogic {
	return &CreateTermLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateTermLogic) CreateTerm(req *types.CreateForumTermReq) (*types.BaseMsgResp, error) {
	if req.Name == nil || len(strings.TrimSpace(*req.Name)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "term.nameRequired"))
	}

	var desc *string
	var descFiltered *string
	if req.Desc != nil && len(strings.TrimSpace(*req.Desc)) > 0 {
		parts := strings.Split(strings.TrimSpace(*req.Desc), globalkey.EditorSplitSymbol)
		if len(parts) > 0 {
			desc = pointy.GetPointer(parts[0])
		}
		if len(parts) > 1 {
			descFiltered = pointy.GetPointer(parts[1])
		}
	}

	var meta []*forumclient.MetaInfo
	if req.Meta != nil && len(req.Meta) > 0 {
		for _, v := range req.Meta {
			meta = append(meta, &forumclient.MetaInfo{
				Key:   v.Key,
				Value: v.Value,
			})
		}
	}

	var allMedia []*forumclient.MediaInfo
	newThumbMap := make(map[string]*types.MediaInfo)
	newMediaMap := make(map[string]*types.MediaInfo)
	var newMediaIds []string // 用于查询 attachmentRpc
	var thumbnail *uint32 = pointy.GetPointer(uint32(1))
	var newMedia []*forumclient.MediaInfo
	var newAttachmentIds []string // 用于主动通知 attachmentRpc
	if len(req.AllMedia) > 0 {    // 富文本所有图片
		for _, v := range req.AllMedia {
			allMedia = append(allMedia, &forumclient.MediaInfo{
				Id:  v.Id,
				Url: v.Url,
			})
		}
	}

	if len(req.NewThumb) > 0 { // 封面图
		for _, v := range req.NewThumb {
			if v.Id != nil && len(*v.Id) > 0 {
				if _, ok := newThumbMap[*v.Id]; !ok { // 忽略重复id
					newThumbMap[*v.Id] = v
					newMediaIds = append(newMediaIds, *v.Id)
				}
			} else {
				newMedia = append(newMedia, &forumclient.MediaInfo{
					Thumbnail: thumbnail,
					Order:     v.Order,
					Url:       v.Url,
					Name:      v.Name,
					MimeType:  v.MimeType,
					AltText:   v.AltText,
					MetaData:  v.MetaData,
				})
			}
		}
	}

	if len(req.NewMedia) > 0 { // 富文本新图片
		for _, v := range req.NewMedia {
			if v.Id != nil && len(*v.Id) > 0 {
				if _, ok := newMediaMap[*v.Id]; !ok { // 忽略重复id
					newMediaMap[*v.Id] = v
					newMediaIds = append(newMediaIds, *v.Id)
				}
			} else {
				newMedia = append(newMedia, &forumclient.MediaInfo{
					Order:    v.Order,
					Url:      v.Url,
					Name:     v.Name,
					MimeType: v.MimeType,
					AltText:  v.AltText,
					MetaData: v.MetaData,
				})
			}
		}
	}

	if len(newMediaIds) > 0 {
		res, err := l.svcCtx.AttachmentRpc.BackendGetFileList(l.ctx, &attachmentclient.FileListReq{
			Ids: pointy.GetPointer(strings.Join(newMediaIds, ",")),
		})
		if err != nil {
			return nil, err
		}

		if len(res.List) > 0 {
			for _, v := range res.List {
				if v.Id != nil && len(*v.Id) > 0 {
					var url string
					if v.Url != nil && len(*v.Url) > 0 {
						url = fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.StaticUrl, *v.Url)
					}
					if len(url) == 0 && v.Path != nil && len(*v.Path) > 0 {
						url = fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.ProxyUrl, *v.Path)
					}

					if media, ok := newThumbMap[*v.Id]; ok {
						newMedia = append(newMedia, &forumclient.MediaInfo{
							Id:        v.Id,
							Thumbnail: thumbnail,
							Order:     media.Order,
							Uri:       media.Url,
							Url:       pointy.GetPointer(url),
							Name:      media.Name,
							MimeType:  media.MimeType,
							AltText:   media.AltText,
							MetaData:  media.MetaData,
						})
						newAttachmentIds = append(newAttachmentIds, *v.Id)
						continue
					}

					if media, ok := newMediaMap[*v.Id]; ok {
						newMedia = append(newMedia, &forumclient.MediaInfo{
							Id:       v.Id,
							Order:    media.Order,
							Uri:      media.Url,
							Url:      pointy.GetPointer(url),
							Name:     media.Name,
							MimeType: media.MimeType,
							AltText:  media.AltText,
							MetaData: media.MetaData,
						})
						newAttachmentIds = append(newAttachmentIds, *v.Id)
					}
				}
			}
		}
	}

	res, err := l.svcCtx.ForumRpc.CreateTerm(l.ctx, &forumclient.TermInfo{
		Name:         req.Name,
		Slug:         req.Slug,
		Taxonomy:     req.Taxonomy,
		ParentId:     req.ParentId,
		GroupId:      req.GroupId,
		Desc:         desc,
		FilteredDesc: descFiltered,
		Sort:         req.Sort,
		Status:       req.Status,
		Meta:         meta,
		AllMedia:     allMedia,
		NewMedia:     newMedia,
	})
	if err != nil {
		return nil, err
	}

	if len(newAttachmentIds) > 0 {
		_, err = l.svcCtx.AttachmentRpc.CreateFileLog(l.ctx, &attachmentclient.CreateFileLogReq{
			FileIds:    newAttachmentIds,
			Put:        pointy.GetPointer(uint32(1)),
			Thumbnail:  pointy.GetPointer(uint32(1)),
			ObjectId:   pointy.GetPointer(res.Id),
			ObjectType: pointy.GetPointer(uint32(globalkey.AttachmentLogTypeForumTerm)),
		})
		if err != nil {
			logx.Errorw("CreateTerm CreateFileLog err", logx.Field("detail", err.Error()))
		}
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
